package com.cuz.for2024;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

public class T39 {


    public static void main(String[] args) {
        System.out.println(new T39().combinationSum(new int[]{2, 3, 6, 7}, 7));
    }

    public List<List<Integer>> combinationSum(int[] candidates, int target) {

        Arrays.sort(candidates);
        List<List<Integer>> res = new ArrayList<>();
        for (int i = 0; i < candidates.length; i++) {
            if (i > 0 && candidates[i] == candidates[i - 1]) {
                continue;
            }
            LinkedList<Integer> tempResult = new LinkedList<>();
            tempResult.add(candidates[i]);
            process(candidates, target - candidates[i], i, res, tempResult);
        }

        return res;
    }

    private void process(int[] candidates, int target,
                         int index, List<List<Integer>> res,
                         LinkedList<Integer> tempResult) {

        if (target == 0) {
            res.add(new ArrayList<>(tempResult));
            return;
        }
        if (index == candidates.length) {
            return;
        }
        if (candidates[index] > target) {
            return;
        }

        // 不用这个数
        process(candidates, target, index + 1, res, tempResult);

        int nowCanUse = candidates[index];
        if (nowCanUse > target) {
            return;
        }

        for (int useCount = 1; useCount <= target / nowCanUse; useCount++) {
            for (int i = 0; i < useCount; i++) {
                tempResult.addLast(nowCanUse);
            }
            process(candidates, target - useCount * nowCanUse, index + 1, res, tempResult);
            for (int i = 0; i < useCount; i++) {
                tempResult.removeLast();
            }
        }
    }
}
